package com.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.domain.RolePermissions;
import com.core.domain.Roles;
import com.core.domain.UserRoles;
import com.core.dto.RoleInfoDto;
import com.core.mapper.RolePermissionsMapper;
import com.core.mapper.UserRolesMapper;
import com.core.resp.AjaxResponse;
import com.core.resp.PageResult;
import com.core.service.RolesService;
import com.core.mapper.RolesMapper;
import com.core.utils.IdGeneratorSnowFlake;
import com.core.vo.RolePermissionVo;
import com.core.vo.RoleVo;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author legion
 * @description 针对表【roles】的数据库操作Service实现
 * @createDate 2025-06-02 16:20:41
 */
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {

    @Autowired
    private RolesMapper rolesMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private RolePermissionsMapper rolePermissionsMapper;

    @Override
    public PageResult<RoleInfoDto> selectPage(Long pageSize, Long pageNum, RoleInfoDto roleInfoDto) {
        Long startIndex = (pageNum - 1) * pageSize;
        List<RoleInfoDto> roleInfoDtos = rolesMapper.selectPage(pageSize, startIndex, roleInfoDto.getName());
        LambdaQueryWrapper<Roles> queryWrapper = new LambdaQueryWrapper<>();
        if (roleInfoDto != null && !StringUtil.isNullOrEmpty(roleInfoDto.getName())) {
            queryWrapper.eq(Roles::getName, roleInfoDto.getName());
        }
        Long total = rolesMapper.selectCount(queryWrapper);
        PageResult<RoleInfoDto> pageResult = new PageResult<>();
        pageResult.setPageNum(pageNum);
        pageResult.setPageSize(pageSize);
        pageResult.setTotal(total);
        pageResult.setData(roleInfoDtos);
        return pageResult;
    }

    @Override
    public AjaxResponse addRole(RoleVo roleVo) {
        try {
            Roles roles = new Roles();
            roles.setId(IdGeneratorSnowFlake.snowFlakeId());
            roles.setName(roleVo.getName());
            roles.setDescription(roleVo.getDescription());
            rolesMapper.insert(roles);
        } catch (Exception e) {
            if (e.getMessage().contains("Duplicate entry")) {
                return AjaxResponse.error(405, "角色已经存在");
            }
            log.error(e.getMessage());
        }

        return AjaxResponse.success(200, "添加成功", null);
    }

    @Override
    public AjaxResponse deleteRoles(List<Long> ids) {
        LambdaQueryWrapper<UserRoles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(UserRoles::getRoleId, ids);
        Long count = userRolesMapper.selectCount(queryWrapper);
        log.debug("总数：" + count);
        if (count != 0L) {
            return AjaxResponse.error(405, "有用户关联此角色，删除失败");
        }
        rolesMapper.deleteBatchIds(ids);
        return AjaxResponse.success(200, "删除成功", null);
    }

    @Override
    public void updateRole(RoleInfoDto roleInfoDto) {
        rolesMapper.updateDescriptionById(roleInfoDto);
    }

    @Transactional
    @Override
    public void updatePermission(RolePermissionVo rolePermissionVo) {
        if (!rolePermissionVo.getPermissions().isEmpty()) {
            LambdaQueryWrapper<RolePermissions> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePermissions::getRoleId, rolePermissionVo.getId());
            queryWrapper.notIn(RolePermissions::getPermissionId, rolePermissionVo.getPermissions());
            rolePermissionsMapper.delete(queryWrapper);
            rolePermissionsMapper.insertPermission(rolePermissionVo);
        } else {
            LambdaQueryWrapper<RolePermissions> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(RolePermissions::getRoleId, rolePermissionVo.getId());
            rolePermissionsMapper.delete(queryWrapper);
        }
    }

    @Override
    public List<Roles> getAllRoles() {
        return rolesMapper.selectList(null);
    }
}




